package com.iye.puretennis.helper;

import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Base64;
import android.util.Log;
import com.iye.puretennis.activity.MainTabsActivity;
import com.iye.puretennis.activity.ProfileActivity;
import com.iye.puretennis.custom.AccessCallBack;
import com.iye.puretennis.custom.CustomHttpDelete;
import com.iye.puretennis.domain.*;
import com.iye.puretennis.fragment.MyGroupsFragment;
import com.iye.puretennis.utils.ImageUtils;
import com.iye.puretennis.utils.JsonUtils;
import com.iye.puretennis.utils.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chuanbao on 2014/11/7.
 */
public class ServerAccessHelper {
    public static final String TAG = "ServerAccessHelper";

    private static HttpParams getHttpParams() {
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                30000);
        HttpConnectionParams.setSoTimeout(httpParams,
                30000);
        return httpParams;
    }

    // 获得Get请求对象request
    private static HttpGet getHttpGet(String url, String token) {
        HttpGet get = new HttpGet(url);
        //GOT access token
        get.addHeader("Access_Token", token);
        get.addHeader("Content-Type", "application/json;charset=utf-8");
        get.addHeader("User-Agent", "imgfornote");
        return get;
    }

    // 获得Post请求对象request
    private static HttpPost getHttpPost(String url, String token) {
        HttpPost post = new HttpPost(url);
        //GOT access token
        post.addHeader("Access_Token", token);
        post.addHeader("Content-Type", "application/json");
        post.addHeader("User-Agent", "imgfornote");
        return post;
    }


    // 获得Delete请求对象request
    private static CustomHttpDelete getHttpDelete(String url, String token) {
        CustomHttpDelete delete = new CustomHttpDelete(url);
        //GOT access token
        delete.addHeader("Access_Token", token);
        delete.addHeader("Content-Type", "application/json");
        delete.addHeader("User-Agent", "imgfornote");
        return delete;
    }

    // 根据请求获得响应对象response
    private static HttpResponse getHttpResponse(HttpGet request) throws IOException {
        return new DefaultHttpClient(getHttpParams()).execute(request);
    }

    // 根据请求获得响应对象response
    private static HttpResponse getHttpResponse(HttpPost request) throws IOException {
        return new DefaultHttpClient(getHttpParams()).execute(request);
    }

    // 根据请求获得响应对象response
    private static HttpResponse getHttpResponse(CustomHttpDelete request) throws IOException {
        return new DefaultHttpClient(getHttpParams()).execute(request);
    }


    // 发送Post请求，获得响应查询结果
    public static String queryStringForPost(String url, String token, StringEntity paramEntity) {
        // 根据url获得HttpPost对象
        HttpPost request = getHttpPost(url, token);
        String result = null;
        try {
            if (paramEntity != null) {
                request.setEntity(paramEntity);
            }
            // 获得响应对象
            HttpResponse response = getHttpResponse(request);
            // 判断是否请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获得响应
                result = EntityUtils.toString(response.getEntity());
                return result;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            result = Constant.RESPONSE_BADLY;
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result = Constant.RESPONSE_BADLY;
            return result;
        }
        return null;
    }

    // 发送Get请求，获得响应查询结果
    public static String queryStringForGet(String url, String token) {
        // 获得HttpGet对象
        HttpGet request = getHttpGet(url, token);
        String result;
        try {
            // 获得响应对象
            HttpResponse response = getHttpResponse(request);
            // 判断是否请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获得响应
                result = EntityUtils.toString(response.getEntity());
                return result;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            result = Constant.RESPONSE_BADLY;
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result = Constant.RESPONSE_BADLY;
            return result;
        }
        return null;
    }

    public static String queryStringForDelete(String url, String token, StringEntity paramEntity) {
        // 获得HttpGet对象
        CustomHttpDelete delete = getHttpDelete(url, token);
        String result = null;

        try {

            if (paramEntity != null) {
                delete.setEntity(paramEntity);
            }
            // 获得响应对象
            HttpResponse response = getHttpResponse(delete);
            // 判断是否请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获得响应
                result = EntityUtils.toString(response.getEntity());
                return result;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            result = Constant.RESPONSE_BADLY;
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            result = Constant.RESPONSE_BADLY;
            return result;
        }
        return null;
    }

    public static Group loadGroup(final String groupGuid, final String access_token, boolean groupOwner) {
        String result = queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.GROUP) + "?groupGuid=" + groupGuid, access_token);

        if (!Constant.RESPONSE_BADLY.equals(result)) {
            try {
                JSONObject json = new JSONObject(result);

                String guid = json.getString("guid");

                String name = json.getString("name");

                JSONObject owner = json.getJSONObject("owner");

                String ownerGuid = owner.getString("guid");

                String ownerName = owner.getString("name");

                String ownerAvatar = owner.getString("avatar");

                int activity = json.getInt("activity");

                int participantsAmount = json.getInt("participantsAmount");

                boolean inGroup = json.getBoolean("inGroup");

                String access = json.getString("access");

                String description = json.getString("description");

                Group group = new Group(guid, name, ownerGuid, ownerName, ownerAvatar, activity, participantsAmount, inGroup, access, description);


                List<UserInfo> groupParticipants = new ArrayList<UserInfo>();

                JSONArray groupParticipantsArray = json.getJSONArray("dataSource");
                int length = groupParticipantsArray.length();
                for (int i = 0; i < length; i++) {
                    JSONObject groupParticipantObj = groupParticipantsArray.getJSONObject(i);
                    boolean isRequest = groupParticipantObj.getBoolean("isRequest");

                    if (isRequest && groupOwner) {
                        String requestGuid = groupParticipantObj.getString("guid");
                        JSONObject senderObj = groupParticipantObj.getJSONObject("sender");
                        String userGuid = senderObj.getString("guid");
                        String userName = senderObj.getString("name");
                        String userAvatar = senderObj.getString("avatar");
                        groupParticipants.add(new UserInfo(userGuid, userName, userAvatar, requestGuid, StringUtils.hasText(userAvatar)));
                    } else {
                        JSONObject userObj = groupParticipantObj.getJSONObject("user");
                        String userGuid = userObj.getString("guid");
                        String userName = userObj.getString("name");
                        String userAvatar = userObj.getString("avatar");
                        groupParticipants.add(new UserInfo(userGuid, userName, userAvatar, StringUtils.hasText(userAvatar)));
                    }
                }
                group.setGroupParticipants(groupParticipants);

                return group;
            } catch (JSONException e) {
                Log.d(TAG, "load group detail json parse failed.");
            }
        }
        return null;
    }

    public static UserInfo loadUserInfo(String userGuid, String token) {
        String result = queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.USER_INFORMATION) + "/" + userGuid, token);
        if (!Constant.RESPONSE_BADLY.equals(result)) {
            return JsonUtils.toUserInfo(result);
        }
        return null;

    }


    public static List<MyGroup> loadMyGroups(String token) {
        String result = queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.MY_GROUPS), token);
        List<MyGroup> myGroups = new ArrayList<MyGroup>();
        if (!Constant.RESPONSE_BADLY.equals(result)) {
            try {
                JSONArray groupArray = new JSONArray(result);
                myGroups.add(new MyGroup(Constant.GUID_ALL, Constant.ALL));
                for (int i = 0; i < groupArray.length(); i++) {
                    JSONObject groupJson = groupArray.getJSONObject(i);
                    String guid = groupJson.getString("groupGuid");
                    String name = groupJson.getString("groupName");
                    myGroups.add(new MyGroup(guid, name));
                }
                return myGroups;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    public static String updateLocation(String token, Location location) {

        JSONObject paramJson = new JSONObject();

        try {
            paramJson.put("city", location.getCity());
            paramJson.put("latitude", location.getLatitude());
            paramJson.put("longitude", location.getLongitude());
            paramJson.put("lastupdate", location.getLastUpdate());
            StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);

            return queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.UPDATE_LOCATION), token, paramEntity);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean logout(String token, String deviceRegistrationID) {

        JSONObject paramJson = new JSONObject();

        try {
            paramJson.put("token", token);
            paramJson.put("deviceType", Constant.ANDROID);
            paramJson.put("deviceRegistrationID", deviceRegistrationID);

            StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);

            String result = queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.LOGOUT), token, paramEntity);

            if (!result.equals(Constant.RESPONSE_BADLY)) {
                return true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return false;

    }


    public static UserDetail loadUserDetail(String token) {
        String result = queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.MY_DETAIL), token);
        if (!Constant.RESPONSE_BADLY.equals(result)) {
            return JsonUtils.toUserDetail(result);
        }
        return null;

    }


    public static String login(String username, String password) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postMethod = new HttpPost(RemoteUrlCollections.getUrl(UrlSuffix.LOGIN));
        String auth = username + ":" + password;
        postMethod.addHeader("Authorization", "Basic " + Base64.encodeToString(auth.getBytes(), Base64.NO_WRAP));
        postMethod.addHeader("Content-Type", "application/json");
        postMethod.addHeader("User-Agent", "imgfornote");
        HttpResponse response = null; //执行POST方法
        String rev = null;
        try {
            response = httpClient.execute(postMethod);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == Constant.RESPONSE_STATUS_OK) {
                rev = EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rev;
    }

    public static Bitmap loadUserImage(String userGuid, String token) {
        String result = queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.USER_INFORMATION) + "/" + userGuid + "/image", token);
        if (!Constant.RESPONSE_BADLY.equals(result)) {
            try {
                JSONObject json = new JSONObject(result);
                String imageBase64 = json.getString("base64Code");
                if (StringUtils.hasText(imageBase64)) {
                    return ImageUtils.base64ToBitmap(imageBase64);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void deleteGroup(final String groupGuid, final String token, final AccessCallBack accessCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                JSONObject profileJsonObj = new JSONObject();

                try {
                    profileJsonObj.put("groupGuid", groupGuid);
                    StringEntity paramEntity = new StringEntity(profileJsonObj.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForDelete(RemoteUrlCollections.getUrl(UrlSuffix.GROUP) + "?groupGuid=" + groupGuid, token, paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        accessCallBack.doCallBack();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }


            }
        }).start();
    }


    public static void removeParticipant(final String userGuid, final String groupGuid, final String token, final AccessCallBack accessCallBack) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject paramJson = new JSONObject();
                try {
                    paramJson.put("userGuid", userGuid);
                    paramJson.put("groupGuid", groupGuid);
                    StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                    String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.LEAVE_GROUP), token, paramEntity);
                    if (!Constant.RESPONSE_BADLY.equals(result)) {
                        accessCallBack.doCallBack();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
